import React, { useState, useEffect } from "react";
import "./index.scss";
import {
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  PieChartOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PoweroffOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Button, Menu } from "antd";
import logo from "@/assets/images/logo.png";
import smallLogo from "@/assets/images/small-logo.png";
import { useNavigate, useLocation, Outlet } from "react-router-dom";

type MenuItem = Required<MenuProps>["items"][number];

const items: MenuItem[] = [
  { key: "/home", icon: <PieChartOutlined />, label: "Option 1" },
  { key: "/home/twoPage", icon: <DesktopOutlined />, label: "Option 2" },
  { key: "/home/threePage", icon: <ContainerOutlined />, label: "Option 3" },
  {
    key: "4",
    label: "Navigation One",
    icon: <MailOutlined />,
    children: [
      { key: "41", label: "Option 5" },
      { key: "42", label: "Option 6" },
      { key: "43", label: "Option 7" },
      { key: "44", label: "Option 8" },
    ],
  },
  {
    key: "5",
    label: "Navigation Two",
    icon: <AppstoreOutlined />,
    children: [
      { key: "51", label: "Option 9" },
      { key: "52", label: "Option 10" },
    ],
  },
];

interface LevelKeysProps {
  key?: string;
  children?: LevelKeysProps[];
}

/**收集 menu 层级 */
const getLevelKeys = (items1: LevelKeysProps[]) => {
  const key: Record<string, number> = {};
  const func = (items2: LevelKeysProps[], level = 1) => {
    items2.forEach(item => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};

const levelKeys = getLevelKeys(items as LevelKeysProps[]);

const Index: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };
  const menuWidth = collapsed ? 90 : 250;
  const navigate = useNavigate();
  const location = useLocation();
  const logout = () => {
    navigate("/login");
  };

  const [stateOpenKeys, setStateOpenKeys] = useState(["1"]);
  /**只展开当前父级菜单：点击父级菜单事件 */
  const onOpenChange: MenuProps["onOpenChange"] = openKeys => {
    const currentOpenKey = openKeys.find(key => stateOpenKeys.indexOf(key) === -1);
    // open
    if (currentOpenKey !== undefined) {
      const repeatIndex = openKeys
        .filter(key => key !== currentOpenKey)
        .findIndex(key => levelKeys[key] === levelKeys[currentOpenKey]);

      setStateOpenKeys(
        openKeys
          // remove repeat key
          .filter((_, index) => index !== repeatIndex)
          // remove current level all child
          .filter(key => levelKeys[key] <= levelKeys[currentOpenKey])
      );
    } else {
      // close
      setStateOpenKeys(openKeys);
    }
  };

  const [selectRoute, setSelectRoute] = useState("/home");
  const changePage = (values: any) => {
    navigate(values.key);
  };
  useEffect(() => {
    setSelectRoute(location.pathname);
  }, [location]);

  return (
    <div className="home_wrap">
      <div className="home_menu_wrap" style={{ width: menuWidth }}>
        <div className="home_title_wrap flex_row_align_center">
          {collapsed ? (
            <img className="home_small_logo" src={smallLogo} alt="home-small-logo" />
          ) : (
            <img className="home_logo" src={logo} alt="home-logo" />
          )}
        </div>
        <div className="home_operation_wrap flex_row_align_center">
          <Button type="primary" shape="round" ghost onClick={toggleCollapsed}>
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          </Button>
          {!collapsed && (
            <div className="after_btn">
              <Button type="primary" shape="round" ghost icon={<PoweroffOutlined />} onClick={logout} />
            </div>
          )}
        </div>
        <Menu
          selectedKeys={[selectRoute]}
          mode="inline"
          theme="dark"
          inlineCollapsed={collapsed}
          items={items}
          openKeys={stateOpenKeys}
          onOpenChange={onOpenChange}
          className="home_menu"
          onSelect={changePage}
        />
      </div>
      <div className="router_wiew" style={{ width: `calc(100% - ${menuWidth}px)` }}>
        <Outlet />
      </div>
    </div>
  );
};
export default Index;
